package com.iot.service.mqtt.service.auth.sql;

import com.iot.service.mqtt.service.auth.AbstractTlAuthentication;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hszhou
 * @Date: 2025/5/10 16:35
 * @Description: 基于数据的用户名密码认证
 */
@Service
@Slf4j
public class SqlTlAuthentication extends AbstractTlAuthentication {


    @Override
    public boolean authenticate(String username, String password) {
        log.info("进入sql认证");

        List<SqlEntityInfo> entityInfos = getConfigs();

        for (SqlEntityInfo entityInfo : entityInfos) {
            HikariConfig config = new HikariConfig();
            String url = String.format("jdbc:mysql://%s:%s/%s", entityInfo.getHost(), entityInfo.getPort(), entityInfo.getDatabase());
            config.setJdbcUrl(url);
            config.setUsername(entityInfo.getUsername());
            config.setPassword(entityInfo.getPassword());
            config.setDriverClassName(entityInfo.getDriverClassName());
            try(HikariDataSource dataSource = new HikariDataSource(config)){
                Connection connection = dataSource.getConnection();
                String sql = String.format("SELECT COUNT(*) FROM %s WHERE %s = ? AND %s = ?",
                        entityInfo.getTable(),
                        entityInfo.getUsernameColumn(),
                        entityInfo.getPasswordColumn());
                if(connection!=null){
                    try( PreparedStatement preparedStatement = connection.prepareStatement(sql)){
                        preparedStatement.setString(1, username);
                        preparedStatement.setString(2, password);
                        try (ResultSet rs = preparedStatement.executeQuery()) {
                            if (rs.next()) {
                                int count = rs.getInt(1);
                                if (count > 0) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }catch (Exception e) {
                log.error("数据库错误【{}】", e.getMessage());
            }
        }

        return false;
    }

    @Override
    public boolean enabled() {
        return true;
    }

    /**
     * 获取配置的数据库连接配置 (模拟)
     * @author hszhou
     * @datetime: 2025-05-12 16:02:25
     * @return List<SqlEntityInfo>
     **/
    public List<SqlEntityInfo> getConfigs() {
        //认证的接口实例
        List<SqlEntityInfo> entityInfos = new ArrayList<>();

        SqlEntityInfo sqlEntityInfo = new SqlEntityInfo();
        sqlEntityInfo.setHost("127.0.0.1");
        sqlEntityInfo.setPort("3306");
        sqlEntityInfo.setUsername("root");
        sqlEntityInfo.setPassword("kangni");
        sqlEntityInfo.setDatabase("watson");
        sqlEntityInfo.setTable("sys_user");
        sqlEntityInfo.setUsernameColumn("username");
        sqlEntityInfo.setPasswordColumn("password");
        sqlEntityInfo.setDriverClassName("com.mysql.cj.jdbc.Driver");
        entityInfos.add(sqlEntityInfo);


        return entityInfos;
    }
}
